package 课上练习0422_scala
import 课上练习0422_scala.Scala_04_thread.Consumer.{flag, tickets}

import scala.util.control.Breaks.{break, breakable}
import scala.util.{Failure, Success}

/**
 * 多线程，synchronized
 */
object Scala_04_thread {
  def main(args: Array[String]): Unit = {
    new Consumer().start()
    new Consumer().start()
    new Consumer().start()
    new Consumer().start()
  }

  class Consumer extends Thread {
    override def run(): Unit = {
      breakable {
        while (flag) {
          Consumer.synchronized {
            if (tickets.remain == 0) {
              flag = false
              break()
            }
            tickets.remain -= 1
            println(s"${Thread.currentThread().getId}售出1张票，余量：${tickets.remain}")
            Thread.sleep(100)
          }
        }
      }
    }
  }
  object Consumer {
    var flag = true
    val tickets: Ticket = Ticket(20)  //20张票
  }
  case class Ticket(var remain: Int)
}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * 多线程，Future
 */
object Scala_04_future {
  def main(args: Array[String]): Unit = {
    val future = Future {
      Thread.sleep(2000)
      1
    }

    // 阻塞获取，一般用于测试
//    println(Await.result(future, 2.seconds))

    // 回调获取，推荐使用
    future.onComplete {
      case Success(value) => println(value)
      case Failure(exception) => println(exception.getMessage)
    }
    Thread.sleep(2100)
  }
}


